import { Suggestion, SearchResult } from '@/types/data'
import { SearchAction } from '@/types/store'
import { getHistory, setHistory } from '@/utils/storage'

type SearchState = {
  suggestion: Suggestion,
  histories: string[],
  // 存放搜索的结果
  results: SearchResult,
}

const initialState: SearchState = {
  suggestion: [],
  histories: getHistory(),
  results: {} as SearchResult

}

const Search = (state = initialState, action: SearchAction): SearchState => {
  switch (action.type) {
    case 'search/suggestion':
      return {
        ...state,
        suggestion: action.payload,
      }
    case 'search/saveHistories':
      // 保存历史记录
      setHistory(action.payload)
      return {
        ...state,
        histories: action.payload
      }
    case 'search/saveHistoryResult':
      return {
        ...state,
        results: {
          ...state.results,
          results: action.payload.results
        }
      }
    default:
      return state
  }
}

export default Search